package cn.vihub.service.impl;

import cn.vihub.param.ShopRoleParam;
import cn.vihub.param.ShopUserParam;
import cn.vihub.pojo.ShopRoleToMenu;
import cn.vihub.pojo.ShopUserToRole;
import cn.vihub.service.ShopRoleToMenuService;
import cn.vihub.service.ShopUserToRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.vihub.pojo.ShopRole;
import cn.vihub.service.ShopRoleService;
import cn.vihub.mapper.ShopRoleMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 64452
* @description 针对表【shop_role】的数据库操作Service实现
* @createDate 2025-07-17 20:43:24
*/
@Service
public class ShopRoleServiceImpl extends ServiceImpl<ShopRoleMapper, ShopRole>
    implements ShopRoleService{

    @Autowired
    private ShopUserToRoleService shopUserToRoleService;

    @Autowired
    private ShopRoleToMenuService shopRoleToMenuService;


    @Override
    public IPage<ShopRole> selectByPage(ShopRoleParam shopRoleParam) {

        IPage<ShopRole> iPage = new Page<>(shopRoleParam.getPage(), shopRoleParam.getLimit());

        LambdaQueryWrapper<ShopRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 模糊查询
        lambdaQueryWrapper.like(StringUtils.isNotBlank(shopRoleParam.getName()), ShopRole::getName, shopRoleParam.getName());

        return page(iPage, lambdaQueryWrapper);
    }

    /**
     * 通过用户id获取用户所关联的角色列表
     * @param shopUserParam
     * @return
     */
    @Override
    public List<ShopRole> getRoleListByUserId(ShopUserParam shopUserParam) {

        // 查询关联的角色id
        List<ShopUserToRole> shopUserToRoleList = shopUserToRoleService.listByUserId(shopUserParam.getId());
        // 把角色的id存入list
        List<Integer> roleList = shopUserToRoleList.stream().map(ShopUserToRole::getRoleId).collect(Collectors.toList());

        return listByIds(roleList);

    }

    /**
     * 角色绑定菜单
     * @param shopRoleParam
     * @return
     */
    @Override
    public Boolean bindMenu(ShopRoleParam shopRoleParam) {

        // 查询旧的绑定如果存在就删除
        shopRoleToMenuService.removeByRoleId(shopRoleParam.getId());

        Integer roleId = shopRoleParam.getId();
        List<Integer> menuIdList = shopRoleParam.getMenuIdList();

        List<ShopRoleToMenu> list = new ArrayList<>();
        for (Integer menuId : menuIdList){
            ShopRoleToMenu shopRoleToMenu = new ShopRoleToMenu();
            shopRoleToMenu.setRoleId(roleId);
            shopRoleToMenu.setMenuId(menuId);
            list.add(shopRoleToMenu);
        }

        return shopRoleToMenuService.saveBatch(list);
    }






















}




